﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace FDStudio.Core.Utils
{
    /*
    CreatedOn: 2018-01-31
    CreatedBy: Jackie Lee(天宇遊龍)
    */
    /// <summary>
    /// 数据查询帮助
    /// </summary>
    public class SqlCommHelper
    {
        /// <summary>
        /// 添加参数到cmd
        /// </summary>
        /// <param name="cmd">IDbCommand</param>
        /// <param name="param">参数</param>
        public static void AddParameter(IDbCommand cmd, object param)
        {
            if (param == null)
                return;
            if (param is IDbDataParameter)
            {
                var p = (IDbDataParameter)param;
                AddParameter(cmd, p.ParameterName, p.Value);
                return;
            }
            if (param is IDbDataParameter[])
            {
                var ps = (IDbDataParameter[])param;
                foreach (var p in ps)
                {
                    AddParameter(cmd, p.ParameterName, p.Value);
                }
                return;
            }
            if (param is IDictionary<string, object>)
            {
                var items = param as IDictionary<string, object>;
                foreach (var p in items)
                {
                    AddParameter(cmd, $"@{p.Key}", p.Value);
                }
                return;
            }
            var type = param.GetType();
            var props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            var parameters = new List<IDbDataParameter>();
            foreach (var p in props)
            {
                AddParameter(cmd, $"@{p.Name}", p.GetValue(param));
            }
        }

        /// <summary>
        /// 添加Cmd参数
        /// </summary>
        /// <param name="cmd">IDbCommand</param>
        /// <param name="name">参数名</param>
        /// <param name="value">参数值</param>
        public static void AddParameter(IDbCommand cmd, string name, object value)
        {
            var cp = cmd.CreateParameter();
            cp.ParameterName = name;
            if (value == null)
            {
                cp.Value = DBNull.Value;
            }
            else
            {
                cp.Value = value;
            }
            cmd.Parameters.Add(cp);
        }
    }
}
